import { useParams } from '@/router/hooks';
import { Button, message } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import PaginationTable from '../../components/PaginationTable';
import {
  BaseQuestionType,
  FeedbackQuestionType,
  FreqQuestionType,
  KnowMenu,
  QuestionType,
  UnknowQuestionType,
} from '@/types/know/know';
import SubPageHeader from '../../components/SubPageHeader';
import SubPageContent from '../../components/SubPageContent';
import knowService from '@/api/services/knowService';
import dayjs from 'dayjs';
import MarkModal from './components/MarkModal';
import './styles/govern.scss';
import SubPageTabs from '../../components/SubPageTabs';
import { SvgIcon } from '@/components/icon';

const Govern = ({ onBack }: { onBack: () => void }) => {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [searchText, setSearchText] = useState('');
  const [currentMarkQA, setCurrentMarkQA] = useState<BaseQuestionType | null>(null);
  const [markModalVisible, setMarkModalVisible] = useState(false);
  const [refreshUnknown, setRefreshUnknown] = useState(0);
  const [refreshFrequent, setRefreshFrequent] = useState(0);
  const [refreshFeedback, setRefreshFeedback] = useState(0);

  const { appId = '' } = useParams() as { appId: string };

  const getType = () => {
    return selectedIndex === 0
      ? QuestionType.Unknown
      : selectedIndex === 1
      ? QuestionType.Feedback
      : QuestionType.Frequent;
  };

  const onMarkClicked = (qa: BaseQuestionType) => {
    setCurrentMarkQA(qa);
    setMarkModalVisible(true);
  };

  const onIgnore = async (data: BaseQuestionType) => {
    try {
      const type = getType();

      await knowService.postMarkQuestion({
        id: data?._id || data?.keyQuestionId,
        appId,
        datas:
          type == QuestionType.Feedback
            ? [
                {
                  q: data?.keyQuestionText,
                  a: data?.keyQuestionAnswer,
                  question_id: data?.keyQuestionId,
                },
              ]
            : data?.questionList?.map((item) => {
                return {
                  q: item.text,
                  a: item.answer,
                  question_id: item.questionId,
                };
              }) || [],
        is_ignore: true,
        type: type,
      });
      data.status = 2;
    } catch (error) {
      console.error(error);
    }
  };

  const onIgnreItems = async (items: BaseQuestionType[]) => {
    const promises = items.map(async (item) => {
      await onIgnore(item);
    });
    await Promise.all(promises);
    message.success('忽略成功');
    refreshData();
  };

  const refreshData = () => {
    switch (selectedIndex) {
      case 0:
        setRefreshUnknown((prev) => prev + 1);
        break;
      case 1:
        setRefreshFeedback((prev) => prev + 1);
        break;
      case 2:
        setRefreshFrequent((prev) => prev + 1);
        break;
    }
  };

  const unknownColumns = [
    {
      title: '问题',
      dataIndex: 'keyQuestionText',
      key: 'keyQuestionText',
    },
    {
      title: '相关问题数',
      width: '10%',
      dataIndex: 'total',
      key: 'total',
      render: (total: number) => {
        return <div>{total || 0}</div>;
      },
    },
    {
      title: '状态',
      width: '10%',
      dataIndex: 'status',
      key: 'status',
      render: (_, record: UnknowQuestionType) => {
        return <div>{`${record.proTotal}/${record.total ?? 1}`}</div>;
      },
    },
    {
      title: '操作',
      width: '10%',
      key: 'operation',
      render: (_, record: UnknowQuestionType) => (
        <div className="flex">
          <Button size="small" type="text" onClick={() => onMarkClicked(record)}>
            <span className="flex items-center text-primary">
              <SvgIcon icon="message-ic20" size="20" className="mr-1" />
              标注答案
            </span>
          </Button>
          <Button size="small" type="text" onClick={() => onIgnreItems([record])}>
            <span className="flex items-center text-primary">
              <SvgIcon icon="message-ic21" size="20" className="mr-1" />
              忽略
            </span>
          </Button>
        </div>
      ),
    },
  ];

  const frequentColumns = [
    {
      title: '问题',
      dataIndex: 'keyQuestionText',
      key: 'keyQuestionText',
    },
    {
      title: '相关问题数',
      width: '10%',
      dataIndex: 'total',
      key: 'total',
      render: (total: number) => {
        return <div>{total || 0}</div>;
      },
    },
    {
      title: '状态',
      width: '10%',
      dataIndex: 'status',
      key: 'status',
      render: (_, record: FreqQuestionType) => {
        return <div>{`${record.proTotal}/${record.total ?? 1}`}</div>;
      },
    },
    // {
    //   title: '触发次数',
    //   width: '10%',
    //   dataIndex: 'questionList',
    //   key: 'questionList',
    //   render: (_, record: FreqQuestionType) => {
    //     return <div>{record?.frequence || 0}</div>;
    //   },
    // },
    {
      title: '操作',
      width: '10%',
      key: 'operation',
      render: (_, record: FreqQuestionType) => (
        <div className="flex">
          <Button size="small" type="text" onClick={() => onMarkClicked(record)}>
            <span className="flex items-center text-primary">
              <SvgIcon icon="message-ic20" size="20" className="mr-1" />
              标注答案
            </span>
          </Button>
          <Button size="small" type="text" onClick={() => onIgnreItems([record])}>
            <span className="flex items-center text-primary">
              <SvgIcon icon="message-ic21" size="20" className="mr-1" />
              忽略
            </span>
          </Button>
        </div>
      ),
    },
  ];

  const feedbackColumns = [
    {
      title: '问题',
      dataIndex: 'keyQuestionText',
      key: 'keyQuestionText',
    },
    {
      title: '反馈',
      dataIndex: 'feedback',
      key: 'feedback',
      render: (_, record: FeedbackQuestionType) => {
        return <div>{record?.feedback}</div>;
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render: (_, record: FeedbackQuestionType) => {
        return <div>{dayjs(record?.updateTime).format('YYYY-MM-DD HH:mm:ss')}</div>;
      },
    },
    {
      title: '操作',
      width: '10%',
      key: 'operation',
      render: (_, record: FeedbackQuestionType) => (
        <div className="flex">
          <Button size="small" type="text" onClick={() => onMarkClicked(record)}>
            <span className="flex items-center text-primary">
              <SvgIcon icon="message-ic20" size="20" className="mr-1" />
              标注答案
            </span>
          </Button>
          <Button size="small" type="text" onClick={() => onIgnreItems([record])}>
            <span className="flex items-center text-primary">
              <SvgIcon icon="message-ic21" size="20" className="mr-1" />
              忽略
            </span>
          </Button>
        </div>
      ),
    },
  ];

  const selectOperators = [
    {
      name: '忽略',
      onClick: async (items: any[]) => {
        onIgnreItems(items);
      },
    },
  ];

  const menus: KnowMenu[] = useMemo(() => {
    return [
      {
        key: 0,
        title: '未知问题',
        children: (
          <PaginationTable
            refreshKey={refreshUnknown}
            rowKey="_id"
            columns={unknownColumns}
            searchText={searchText}
            api={knowService.getUnknownQuestions}
            // selectOperators={selectOperators}
          />
        ),
      },
      {
        key: 1,
        title: '点踩问题',
        children: (
          <PaginationTable
            refreshKey={refreshFeedback}
            rowKey="keyQuestionId"
            columns={feedbackColumns}
            searchText={searchText}
            api={knowService.getFeedbackQuestions}
            // selectOperators={selectOperators}
          />
        ),
      },
      {
        key: 2,
        title: '高频问题',
        children: (
          <PaginationTable
            refreshKey={refreshFrequent}
            rowKey="_id"
            columns={frequentColumns}
            searchText={searchText}
            api={knowService.getFrequentQuestions}
            // selectOperators={selectOperators}
          />
        ),
      },
    ];
  }, [searchText, refreshFeedback, refreshFrequent, refreshUnknown, selectedIndex]);

  return (
    <div className="flex h-full flex-col overflow-hidden pb-6">
      <SubPageHeader
        menus={menus}
        title="问题处理"
        onBack={onBack}
        selectedIndex={selectedIndex}
        onChangeIndex={(index) => setSelectedIndex(index)}
        onSearchTextChanged={(text) => setSearchText(text)}
      />
      <SubPageTabs
        menus={menus}
        title="问题处理"
        onBack={onBack}
        selectedIndex={selectedIndex}
        onChangeIndex={(index) => setSelectedIndex(index)}
        onSearchTextChanged={(text) => setSearchText(text)}
      />
      <SubPageContent menus={menus} selectedIndex={selectedIndex} />
      <MarkModal
        type={getType()}
        data={currentMarkQA!}
        open={markModalVisible}
        refresh={refreshData}
        onCancel={() => {
          setMarkModalVisible(false);
        }}
      />
    </div>
  );
};

export default Govern;
